﻿using System.Collections.Generic;

namespace QQ2564874169.RelationalSql
{
    public class DataSort
    {
        public List<string> Sorts { get; }

        public DataSort()
        {
            Sorts = new List<string>();
        }
    }

    public class PageSort : DataSort
    {
        public int PageCount { get; set; }
        public int PageIndex { get; set; }

        public PageSort(int index = 1, int count = 10)
        {
            PageCount = count;
            PageIndex = index;
        }

        public virtual string ToCountSql(string sourceSql)
        {
            return $"SELECT COUNT(1) FROM({sourceSql}) T";
        }

        public virtual string ToDataSql(string sourceSql)
        {
            var start = (PageIndex - 1) * PageCount;
            var end = start + PageCount + 1;
            var ordersql = Sorts.Count > 0 ? this.ToMssql() : "ORDER BY (SELECT 0)";

            return $@"SELECT * FROM (
                        SELECT *,ROW_NUMBER() OVER({ordersql}) PAGEROW FROM ({sourceSql}) T
                      ) T WHERE PAGEROW>{start} AND PAGEROW<{end}";
        }
    }
}
